<template>
  <div class="data-visualization">
    <!-- 年份分布图表 -->
    <div v-if="type === 'year'" class="chart-container">
      <div v-if="loading" class="loading-container">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
      <div v-else-if="!data || data.length === 0" class="empty-container">
        <Icon icon="ant-design:bar-chart-outlined" :size="64" />
        <p>暂无数据</p>
      </div>
      <div v-else ref="yearChartRef" class="chart"></div>
    </div>

    <!-- 机构统计图表 -->
    <div v-else-if="type === 'institution'" class="chart-container">
      <div v-if="loading" class="loading-container">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
      <div v-else-if="!data || data.length === 0" class="empty-container">
        <Icon icon="ant-design:pie-chart-outlined" :size="64" />
        <p>暂无数据</p>
      </div>
      <div v-else ref="institutionChartRef" class="chart"></div>
    </div>

    <!-- 发明人统计图表 -->
    <div v-else-if="type === 'inventor'" class="chart-container">
      <div v-if="loading" class="loading-container">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
      <div v-else-if="!data || data.length === 0" class="empty-container">
        <Icon icon="ant-design:user-outlined" :size="64" />
        <p>暂无数据</p>
      </div>
      <div v-else ref="inventorChartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue';
import { Spin } from 'ant-design-vue';
import { Icon } from '/@/components/Icon';
import * as echarts from 'echarts';

interface Props {
  data: any[];
  type: 'year' | 'institution' | 'inventor';
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
});

const yearChartRef = ref<HTMLElement>();
const institutionChartRef = ref<HTMLElement>();
const inventorChartRef = ref<HTMLElement>();

let yearChart: echarts.ECharts | null = null;
let institutionChart: echarts.ECharts | null = null;
let inventorChart: echarts.ECharts | null = null;

// 初始化年份分布图表
const initYearChart = () => {
  if (!yearChartRef.value || !props.data) return;
  
  yearChart = echarts.init(yearChartRef.value);
  
  const option = {
    title: {
      text: '年份分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params: any) => {
        const data = params[0];
        return `${data.name}年<br/>事件数: ${data.value}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.data.map(item => item.year),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '事件数'
    },
    series: [{
      name: '事件数',
      type: 'bar',
      data: props.data.map(item => item.count),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      }
    }]
  };
  
  yearChart.setOption(option);
};

// 初始化机构统计图表
const initInstitutionChart = () => {
  if (!institutionChartRef.value || !props.data) return;
  
  institutionChart = echarts.init(institutionChartRef.value);
  
  const option = {
    title: {
      text: '机构统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        return `${params.name}<br/>事件数: ${params.value}`;
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [{
      name: '事件数',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      data: props.data.map(item => ({
        value: item.count,
        name: item.institution
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        formatter: '{b}: {c}'
      }
    }]
  };
  
  institutionChart.setOption(option);
};

// 初始化发明人统计图表
const initInventorChart = () => {
  if (!inventorChartRef.value || !props.data) return;
  
  inventorChart = echarts.init(inventorChartRef.value);
  
  const option = {
    title: {
      text: '发明人统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params: any) => {
        const data = params[0];
        return `${data.name}<br/>事件数: ${data.value}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '事件数'
    },
    yAxis: {
      type: 'category',
      data: props.data.map(item => item.inventor),
      axisLabel: {
        formatter: (value: string) => {
          return value.length > 10 ? value.substring(0, 10) + '...' : value;
        }
      }
    },
    series: [{
      name: '事件数',
      type: 'bar',
      data: props.data.map(item => item.count),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
          { offset: 0, color: '#ff9a9e' },
          { offset: 1, color: '#fecfef' }
        ])
      }
    }]
  };
  
  inventorChart.setOption(option);
};

// 渲染图表
const renderChart = () => {
  nextTick(() => {
    switch (props.type) {
      case 'year':
        initYearChart();
        break;
      case 'institution':
        initInstitutionChart();
        break;
      case 'inventor':
        initInventorChart();
        break;
    }
  });
};

// 监听数据变化
watch(() => props.data, () => {
  renderChart();
}, { deep: true });

// 监听loading状态
watch(() => props.loading, () => {
  if (!props.loading) {
    renderChart();
  }
});

// 组件挂载
onMounted(() => {
  renderChart();
});

// 窗口大小变化时重新渲染
window.addEventListener('resize', () => {
  if (yearChart) yearChart.resize();
  if (institutionChart) institutionChart.resize();
  if (inventorChart) inventorChart.resize();
});
</script>

<style scoped lang="less">
.data-visualization {
  width: 100%;
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 350px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #8c8c8c;
  
  p {
    margin-top: 16px;
    font-size: 14px;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #bfbfbf;
  
  p {
    margin-top: 16px;
    font-size: 14px;
  }
}
</style>